const koa = require('koa');
const app = new koa();

const Router = require('koa-router');
const router = new Router();
const { koaBody } = require('koa-body');

const token = 'dkjahkjdahkhkjnhdkajhhkhioau12316456'

app.use(koaBody({ multipart: true }));

app.use(async (ctx, next) => {
    ctx.set('Access-Control-Allow-Origin', 'http://127.0.0.1:5500');
    ctx.set('Access-Control-Allow-Methods', 'GET, POST, PUT, DELETE, OPTIONS');
    ctx.set('Access-Control-Allow-Credentials', 'true');
    ctx.set('Access-Control-Allow-Headers', 'Content-Type, Authorization');

    if (ctx.method === 'OPTIONS') {
        ctx.body = 200;
    } else {
        await next();
    }
});
app.use(async (ctx, next) => {
    if (ctx.url === '/login') { // 登录接口不需要校验 token
        await next();
        return;
    }

    const cookie = ctx.cookies.get('token'); // 不需要指定 httpOnly 选项
    console.log(cookie);

    if (cookie && cookie === token) {
        await next();
    } else {
        ctx.body = {
            code: 401,
            msg: '权限不足',
        };
        return;
    }
});

router.post('/login', (ctx, next) => {
    //登录成功
    //给前端设置登录凭证
    ctx.cookies.set('token', token, {
        expires: new Date(+new Date() + 1000 * 60 * 60 * 24 * 7),
        httpOnly: true,
        signed: false,
        sameSite: 'none',
        secure: ctx.request.protocol === 'https', // 确保安全传输
      });
    ctx.body = {
        code: 200,
        msg: '登录成功'
    }
})
router.get('/home', (ctx, next) => {
 
    ctx.body = {
        code: 200,
        msg: '首页数据',
      };
})

router.post('/login',)
app.use(router.routes())
app.listen(3000, () => {
    console.log('服务器启动成功')
})